// <copyright file="UserRepository.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Data;
using EnterpriseApi.Models;
using Microsoft.EntityFrameworkCore;

namespace EnterpriseApi.Repositories;

/// <summary>
/// 用户仓储实现类，提供用户特有的数据访问操作
/// </summary>
public class UserRepository : Repository<User>, IUserRepository
{
    private readonly AppDbContext _context;

    /// <summary>
    /// 初始化UserRepository的新实例
    /// </summary>
    /// <param name="context">数据库上下文</param>
    public UserRepository(AppDbContext context) : base(context)
    {
        _context = context;
    }

    /// <summary>
    /// 根据用户名获取用户
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns>用户对象，如果不存在则返回null</returns>
    public async Task<User?> GetByUsernameAsync(string username)
    {
        return await _context.Users.FirstOrDefaultAsync(u => u.Username == username);
    }

    /// <summary>
    /// 根据邮箱获取用户
    /// </summary>
    /// <param name="email">邮箱地址</param>
    /// <returns>用户对象，如果不存在则返回null</returns>
    public async Task<User?> GetByEmailAsync(string email)
    {
        return await _context.Users.FirstOrDefaultAsync(u => u.Email == email);
    }

    /// <summary>
    /// 检查用户名是否已存在
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns>用户名是否已存在</returns>
    public async Task<bool> IsUsernameExistsAsync(string username)
    {
        return await _context.Users.AnyAsync(u => u.Username == username);
    }

    /// <summary>
    /// 检查邮箱是否已存在
    /// </summary>
    /// <param name="email">邮箱地址</param>
    /// <returns>邮箱是否已存在</returns>
    public async Task<bool> IsEmailExistsAsync(string email)
    {
        return await _context.Users.AnyAsync(u => u.Email == email);
    }

    /// <summary>
    /// 获取活跃用户列表
    /// </summary>
    /// <returns>活跃用户集合</returns>
    public async Task<IEnumerable<User>> GetActiveUsersAsync()
    {
        return await _context.Users.Where(u => u.IsActive).ToListAsync();
    }

    /// <summary>
    /// 获取特定角色的用户列表
    /// </summary>
    /// <param name="roleId">角色ID</param>
    /// <returns>特定角色的用户集合</returns>
    public async Task<IEnumerable<User>> GetUsersByRoleAsync(int roleId)
    {
        return await _context.Users.Where(u => u.RoleId == roleId).ToListAsync();
    }
}